import formCreate from '@form-create/element-ui'
import { getGlobalConfig } from '@vipl520/utils'

function createFetch(baseUrl) {
  return (options) => {
    const globalConfig = getGlobalConfig()
    const headers = {
      'Access-Token': globalConfig.AccessToken,
      'Project-Type': globalConfig.ProjectType,
      'Addon-Name': globalConfig.AddonName,
      ...options.headers // 合并用户提供的headers
    }

    const params = new URLSearchParams([['_ajax', 1], ...(options.data ? Object.entries(options.data) : [])])

    let body
    if (options.method.toUpperCase() !== 'GET') {
      body = options.data ? JSON.stringify(options.data) : undefined
    }

    console.log('options', options)
    const url = new URL(baseUrl + options.action)
    url.search = params.toString()

    fetch(url, {
      headers,
      method: options.method,
      body
    })
      .then((res) => res.json())
      .then((data) => options.onSuccess(data))
      .catch((e) => options.onError(e))
  }
}

const baseUrl = import.meta.env.VITE_BASE_URL

// 使用创建的 fetch 方法初始化 viewForm 和 designerForm
const viewForm = formCreate
viewForm.fetch = createFetch(baseUrl)

const designerForm = formCreate.factory()
designerForm.fetch = createFetch(baseUrl)

export default viewForm
export { designerForm }
